var param = {},
    formId = 'nonStandardDrugsForm',
    url = "/openx/goods/nonStandardDrugsService/listNonStandardGoodsByPage",
    topChannelCodeList = {},
    channelMap = new Map();

(function () {
    initTopChannel("topChannelCode");
    param.nonStandardDrugsForm = $.openx.getJsonObj(formId);
    param.nonStandardDrugsForm["topChannelCode"] = "XINGREN";
    var queryTimeStamp = new Date();
    // console.log(topChannelCodeList);
    for (let i = 0; i < topChannelCodeList.length; i++) {
        channelMap.put(topChannelCodeList[i].channelCode, topChannelCodeList[i].name);
    }
    $.openx.initTable("table", url + "?t=" + queryTimeStamp.getTime(), param);
})();

//查询按钮触发
$.openx.query = function () {
    param.nonStandardDrugsForm = $.openx.getJsonObj(formId);
    var queryTimeStamp = new Date();
    $.openx.tableRefresh(url + "?t=" + queryTimeStamp.getTime(), param, param);
}

$.openx.import = function () {
    $("#uploadImgResult").html("");
    $("#excelFileInput").val("");
    initTopChannel("importTopChannelCode");
    $("#import-form").modal("show");
}


function showFormatTopChannelCode(value, row){
    return channelMap.get(row.topChannelCode);
}

async function initTopChannel(second) {
    $X("/boss/channelService", "listAllTopChannel").callx({
        onResult: function (data) {
            if (data) {
                topChannelCodeList = data;
                bindSelectWithData(second, data);
            } else {
                layer.msg("无信息")
            }
        },
        onError: function (error) {
            var res = JSON.parse(error);
            layer.msg(res.message)
        }
    });
}


$.openx.insert = function () {
    initTopChannel("saveTopChannelCode");
    var createForm = "saveNonstandardGoodsForm";
    var innerHtml = $.openx.innerHtml('nonstandardGoodsDialog');
    laytpl(innerHtml).render({}, function (html) {
        $.openx.openLayer(['600', '500'], '新增非标商品', html, false, function () {
            if ($.openx.validation(createForm)) {
                //获取表单数据   
                var param = $.openx.getJsonObj(createForm);
                $X("/goods/nonStandardDrugsService", "save").callx({
                    nonStandardDrugs: param,
                    onResult: function (data) {
                        $.openx.tableRefresh(null, null, true);
                        layer.closeAll();
                        layer.msg("新增成功");
                    },
                    onError: function (error) {
                        var res = JSON.parse(error);
                        layer.msg(res.message)
                    }
                });
            }
        });
    });
}

$.openx.delete = function () {
    $.openx.onClickDelete(function (rows) {
        var ids = new Array();
        for (var i = 0; i < rows.length; i++) {
            ids.push(rows[i].id);
        }
        $X("/goods/nonStandardDrugsService", "delete").callx({
            ids: ids,
            onResult: function (result) {
                layer.closeAll();
                $.openx.tableRefresh(null, null, true);
            },
            onError: function (error) {
            }
        });
    });
}

//检查文件大小和扩展名
function checkFileSizeType(fileId, maxFileSize, fileTypeArr) {
    var file = document.getElementById(fileId).files[0];
    if (!file) {
        layer.tips("请选择文件！", "#excelFileInput", {
            tips: [2, "#f40"]
        })
        return -1;
    }
    //检查文件类型
    if (fileTypeArr && fileTypeArr.length > 0) {
        for (var i = 0; i < fileTypeArr.length; i++) {
            fileTypeArr[i] = fileTypeArr[i].toLowerCase();
        }
        if (fileTypeArr.indexOf(file.name.substring(file.name.lastIndexOf("."), file.name.length).toLowerCase()) === -1) {
            layer.tips("上传文件类型错误！", "#excelFileInput", {
                tips: [2, "#f40"]
            })
            return -1;
        }
    }
    //检查文件大小
    if (file.size > maxFileSize) {
        layer.tips("上传文件不能大于" + (maxFileSize / 1024).toFixed(2) + "KB！", "#excelFileInput", {
            tips: [2, "#f40"]
        })
        return -1;
    }
}

function importExcel() {
    //判断文件大小
    checkFileSizeType('excelFileInput', 10 * 1024 * 1024, '');

    loadFileDataToBase64String('excelFileInput', function (excel) {
        $("#importExcelButton").attr("disabled", true);
        $X("/goods/nonStandardDrugsService", "batchSave").callx({
            topChannelCode: $("#importTopChannelCode").val(),
            base64Str: excel,
            onResult: function (data) {
                $("#importExcelButton").attr("disabled", false);
                if (data && data.length > 0) {
                    $('#uploadImgResult').html(data);
                } else {
                    $('#uploadImgResult').html("已加入导入队列!!!");
                }
            },
            //请求失败执行
            onError: function (error) {
                $("#importExcelButton").attr("disabled", false);
                var res = JSON.parse(error);
                $('#uploadImgResult').html(res.message);
                layer.msg(res.message)
            }
        }, 3000 * 1000);
    });
}

function activityTimeFormat(value, row) {

    var beginTime = row.activityBeginTime;
    var endTime = row.activityEndTime;
    if (beginTime == undefined || endTime == undefined) {
        return "-";
    }

    return $.openx.formatDate(new Date(beginTime), "yyyy-MM-dd hh:mm") + " - " + $.openx.formatDate(new Date(endTime), "yyyy-MM-dd hh:mm");
}

function loadFileDataToBase64String(fileName, callback) {
    var file = document.getElementById(fileName).files[0];
    //读取文件
    var reader = new FileReader();
    reader.onload = function () {
        var result = this.result.split('base64,')[1];
        callback(result);
    }
    reader.readAsDataURL(file);
}

function resetForm() {
    $('#nonStandardDrugsForm')[0].reset();
    $('#channelSelectsId').val(null).trigger('change');
}

function formatCode(value, row) {
    if (value) {
        return '\'' + value;
    } else {
        return '';
    }
}

function showImportDeleteExcel() {
    $("#excelDeleteFileInput").val("");
    $("#import-delete-form").modal("show");
}